package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    public Map<String, Object> loadItemData(Long id) {
        // 判断redis中，是否有id，如果有，取出对应map，直接return

        // 查询spu
        SpuDTO spu = itemClient.querySpuById(id);
        // 查询分类
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        // 查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecs(spu.getCid3());
        // 封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("categories", categories);
        map.put("brand", brand);
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("detail", spu.getSpuDetail());
        map.put("skus", spu.getSkus());
        map.put("specs", specs);

        // 把数据写入redis，key是id，值是这个map
        return map;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    private static final String HTML_DIR = "C:\\lesson\\heima72\\nginx-1.12.2\\html\\item";

    public void createItemHtml(Long id) {
        // 准备上下文，存放模型数据
        Context context = new Context();
        context.setVariables(loadItemData(id));
        // 创建目标静态页面的名称
        File file = new File(HTML_DIR, id + ".html");
        // 创建输出流，关联nginx下的一个文件
        try (PrintWriter writer = new PrintWriter(file, "UTF-8")) {
            // 渲染模板数据，输出到指定的流
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("生成静态页失败，原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    public void deleteItemHtml(Long spuId) {
        File file = new File(HTML_DIR, spuId + ".html");
        if(file.exists()){
            boolean isDelete = file.delete();
            if(!isDelete){
                // 如果是false，证明删除失败
                throw new RuntimeException("数据删除失败！");
            }
        }
    }
}
